package com.sdy.supermarket.web.controller;

import com.sdy.auth.api.AuthApi;
import com.sdy.auth.api.model.AuthDto;
import com.sdy.auth.api.model.UserDto;
import com.sdy.auth.client.service.SsoService;
import com.sdy.common.model.Response;
import com.sdy.common.utils.DesensitizeUtil;
import com.sdy.mvc.controller.BaseController;
import com.sdy.mvc.service.FileService;
import com.sdy.redis.service.RedisService;
import com.sdy.supermarket.biz.constants.RedisConstants;
import com.sdy.supermarket.biz.utils.CopyUtil;
import com.sdy.supermarket.biz.utils.IpUtil;
import com.sdy.supermarket.biz.vo.UserInfoVo;
import com.sdy.usercenter.api.UserQueryApi;
import com.sdy.usercenter.api.dto.RoleDto;
import com.sdy.usercenter.api.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by zzq on 2019/1/10.
 */
@Slf4j
@RestController
public class IndexController extends BaseController {
    @Autowired
    private RedisService redisService;
    @Autowired
    private SsoService ssoService;
    @Autowired
    private AuthApi authApi;
    @Value("${res.app.code}")
    private String appCode;
    @Autowired
    private FileService fileService;
    @Autowired
    private UserQueryApi userQueryApi;

//    @GetMapping("/publicKey")
//    @ResponseBody
//    public Response publicKey(HttpServletRequest request) throws Exception {
//        KeyPair keyPair = EncodeUtil.rsaGenKeyPair();
//        String publicKeyStr = new String(Base64.getEncoder().encode(keyPair.getPublic().getEncoded()));
//        redisService.set(RedisConstants.REDIS_PREFIX + "privateKey_" + getUserId(request), Base64.getEncoder().encode(keyPair.getPrivate().getEncoded()));
//        return Response.success(publicKeyStr);
//    }

    @GetMapping("/userInfo")
    public Response userInfo(HttpServletRequest request) {
        Integer userId = ssoService.getUserInfo(request).getUserId();
        UserDTO user = userQueryApi.getUser(userId);
        user.setIdCard(DesensitizeUtil.hideIdCardNo(user.getIdCard()))
                .setPhone(DesensitizeUtil.hideCellPhone(user.getPhone()));
        record(request);
        AuthDto authTree = authApi.getAuthTree(appCode, userId);
        String fsUploadAddr = fileService.getFsUploadAddr();
        user.setIdCard(DesensitizeUtil.hideIdCardNo(user.getIdCard()))
                .setPhone(DesensitizeUtil.hideCellPhone(user.getPhone()));
        List<RoleDto> roleDtos = userQueryApi.listRoleByIds(user.getRoleIdList());
        UserInfoVo userinfo = CopyUtil.clone(user, UserInfoVo.class);
        userinfo.setOwnDeptName(user.getOwnDeptName());
        userinfo.setOwnDeptId(user.getOwnDeptId());
        List<RoleDto> removeRoleDto = new ArrayList<>();
        for (RoleDto roleDto : roleDtos) {
            if (!roleDto.getCode().contains("gs")) {
                removeRoleDto.add(roleDto);
            }
        }
        roleDtos.removeAll(removeRoleDto);
        userinfo.setRoleDtos(roleDtos);
        Map<String, Boolean> map = authTree.convertToMap();
        List<String> removeKeys = new ArrayList<>();
        for (Map.Entry<String, Boolean> entry : map.entrySet()) {
            if (entry.getValue() == false) {
                removeKeys.add(entry.getKey());
            }
        }
        removeKeys.forEach(key -> {
            map.remove(key);
        });
        userinfo.setAuthTree(map);
        userinfo.setUploadUrl(fsUploadAddr);
        return Response.success(userinfo);
    }

    private void record(HttpServletRequest request) {
        // 获取用户ip
        String ipAddr = IpUtil.getIpAddr(request);
        // 首先记录浏览数量
        if (!redisService.exists(RedisConstants.REDIS_PREFIX_VIEWS + LocalDate.now() + "")) {
            // 有效期为七天
            redisService.set(RedisConstants.REDIS_PREFIX_VIEWS + LocalDate.now() + "", 0, RedisConstants.REDIS_PREFIX_TIME_OUT);
            redisService.incr(RedisConstants.REDIS_PREFIX_VIEWS + LocalDate.now() + "");
        } else {
            redisService.incr(RedisConstants.REDIS_PREFIX_VIEWS + LocalDate.now() + "");
        }
        // 首先判断记录用户访问数的key是否存在，不存在则创建
        if (!redisService.exists(RedisConstants.REDIS_PREFIX_USER_VIEWS + LocalDate.now() + "")) {
            redisService.set(RedisConstants.REDIS_PREFIX_USER_VIEWS + LocalDate.now() + "", 0, RedisConstants.REDIS_PREFIX_TIME_OUT);
        }
        // 记录访问用户数量
        if (!redisService.exists(ipAddr)) {
            // 过期时间为当日最后一秒钟
            redisService.set(ipAddr, "记录此IP", getDieSecond().intValue());
            redisService.incr(RedisConstants.REDIS_PREFIX_USER_VIEWS + LocalDate.now() + "");
        }
    }

    private Long getDieSecond() {
        // 计算出当前时间到当日最后一秒钟的时间差
        LocalDate end = LocalDate.now();
        LocalDateTime endTime = end.atTime(23, 59, 59);
        long endSecond = endTime.toEpochSecond(ZoneOffset.of("+8"));
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.of("+8"));
        return endSecond - nowSecond;
    }

}
